using MySqlConnector;

namespace Front._1118;

public partial class BookAdd : Form
{
    public BookAdd()
    {
        InitializeComponent();
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
         // 1. 获取输入值
        string bookId = textBox1.Text.Trim();
        string isbn = textBox2.Text.Trim();
        string bookName =textBox3.Text.Trim();
        string author = textBox4.Text.Trim();
        string bookCategory = textBox5.Text.Trim();
        

        // 2. 非空校验
        if (string.IsNullOrEmpty(bookId) || string.IsNullOrEmpty(isbn) || 
            string.IsNullOrEmpty(bookName) || string.IsNullOrEmpty(author))
        {
            MessageBox.Show("请填写所有字段！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        // 3. 插入数据库
        string connStr = "server=localhost;port=3306;database=book;user=root;password=123456;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
        string sql = "INSERT INTO book_info (book_id, isbn, book_name, author,book_category) VALUES (@book_id, @isbn, @book_name, @author,@book_category)";

        try
        {
            using (MySqlConnection connection = new MySqlConnection(connStr))
            {
                connection.Open();
                using (MySqlCommand command = new MySqlCommand(sql, connection))
                {
                    // 参数化插入（防SQL注入）
                    command.Parameters.AddWithValue("@book_id", bookId);
                    command.Parameters.AddWithValue("@isbn", isbn);
                    command.Parameters.AddWithValue("@book_name", bookName);
                    command.Parameters.AddWithValue("@author", author);
                    command.Parameters.AddWithValue("@book_category", bookCategory);

                    // 执行插入
                    int rowsAffected = command.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        MessageBox.Show("新增图书成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close(); // 关闭新增窗体
                    }
                    else
                    {
                        MessageBox.Show("新增图书失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("新增失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}